#include <stdio.h>
#include <gmp.h>
#include "gauss-legendre.h"

#define IT_N_SIZE 32

/* variaveis */

mpf_t new_pi, old_pi, new_a, old_a, new_b, old_b;
mpf_t t, ttmp, err;
unsigned long int log2p;

void init_vals(){

	mpf_init(new_pi);
	mpf_init(old_pi);
	mpf_init(new_a);
	mpf_init(old_a);
	mpf_init(new_b);
	mpf_init(old_b);
	mpf_init(t);
	mpf_init(ttmp);
	mpf_init_set_str(err, "1e-10000000", 10);

	log2p = 0;
	mpf_set_ui(old_a, 1);
	mpf_sqrt_ui(old_b, 2);
	mpf_ui_div(old_b, 1, old_b);
	mpf_div_ui(t, old_a, 4);
}

void calc_new_a(){
	mpf_add(new_a, old_b, old_a);
	mpf_div_ui(new_a, new_a, 2);
}

void calc_new_b(){
	mpf_mul(new_b, old_a, old_b);
	mpf_sqrt(new_b, new_b);
}

void t_use_a(){
	mpf_sub(ttmp, old_a, new_a);
}

void t_pre_calc(){
	mpf_pow_ui(ttmp, ttmp, 2);
	mpf_mul_2exp(ttmp, ttmp, log2p);
	log2p++;
}

void set_new_t(){
	mpf_sub(t,t,ttmp);
}

void pi_use_ab(){
	mpf_swap(old_pi, new_pi);
	mpf_add(new_pi, new_a, new_b);
	mpf_swap(old_a, new_a);
	mpf_swap(old_b, new_b);
}

void pi_pre_calc(){
	mpf_pow_ui(new_pi, new_pi, 2);
	mpf_div_2exp(new_pi, new_pi, 2);
}

void pi_end_calc_use_t(){
	mpf_div(new_pi, new_pi, t);
}

int check_erro(){
	mpf_sub(old_pi, new_pi, old_pi);
    mpf_abs(old_pi, old_pi);
	return (mpf_cmp(err, old_pi) < 0);
}

void save_it(char* name){
	static int it = 0;
	FILE *fd;
	char it_name[IT_N_SIZE];

	sprintf(it_name, "%s-it%d.txt", name, ++it);
    fd = fopen(it_name, "w");
    gmp_fprintf(fd, "%.10000000Ff\n", new_pi);
    fclose(fd);
}

void clear_vars(){
	mpf_clear(new_pi);
	mpf_clear(old_pi);
	mpf_clear(new_a);
	mpf_clear(old_a);
	mpf_clear(new_b);
	mpf_clear(old_b);
	mpf_clear(t);
	mpf_clear(ttmp);
	mpf_clear(err);
}
